﻿using Test.Web.Infrastructure;
using System.Collections.Generic;
using System.Web.Mvc;
using Test.Utility.Extensions;
using Test.Site.Data.Models;

namespace Test.Web.Areas.Backstage.Controllers
{
    public class SharedController : AdminBaseController
    {
        [ChildActionOnly]
        public ActionResult _Menu()
        {
            var menuItems = AdminSession.MenuItems;

            var controller = Request.RequestContext.RouteData.Values["Controller"].ToString();
            var action = Request.RequestContext.RouteData.Values["Action"].ToString();

            SetMenuActionStatus(menuItems, controller, action);
            AdminSession = AdminSession;

            return PartialView(menuItems);
        }

        private bool SetMenuActionStatus(IEnumerable<MenuItem> menuItems, string controller, string action)
        {
            bool hasActive = false;
            foreach (var menuItem in menuItems)
            {
                menuItem.IsActive = (menuItem.Action == action && menuItem.Controller == controller)
                                || (menuItem.Controller == controller && menuItem.Action.IsNullOrWhiteSpace());
                menuItem.IsActive |= SetMenuActionStatus(menuItem.ChildrensMenuItem, controller, action);

                hasActive |= menuItem.IsActive;
            }
            return hasActive;
        }

    }
}